﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using IceScream.Models;
using IceScream.Common;

namespace IceScream.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {
        DataEntities storeDB = new DataEntities();
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOnAdmin()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOnAdmin(LogOnModel model, string returnUrl)
        {
            try
            {
                string inputPass = UICommon.Encryption(model.Password);

                var datausername = storeDB.Admins.Where(u => u.UserName == model.UserName && u.Password == inputPass).FirstOrDefault();
                if (datausername != null)
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            catch
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            try
            {
                string inputPass = UICommon.Encryption(model.Password);

                var datausername = storeDB.Users.Where(u => u.Username == model.UserName && u.Password == inputPass && u.Active==true).FirstOrDefault();
                if (datausername != null)
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            catch
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            AccountRegisterModel acc = new AccountRegisterModel()
            {
                sameusername = ""
            };
            return View(acc);
        }

        [HttpPost]
        public ActionResult Register(AccountRegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User UserInDB = new User();
                string username = model.user_name.ToLower();
                string md5Pass = UICommon.Encryption(model.user_pass);

                UserInDB = storeDB.Users.Where(u => u.Username == username).FirstOrDefault();
                if (UserInDB != null)
                {
                    AccountRegisterModel acc = new AccountRegisterModel()
                    {
                        sameusername = "This username have already registered."
                    };
                    return View(acc);
                }
                else
                {
                    User user = new User()
                    {
                        FirstName = model.user_firstn,
                        LastName = model.user_lastn,
                        Password = md5Pass,
                        Phone = model.user_phone,
                        Username = username,
                        Address = model.user_address,
                        Email = model.user_mail,
                        Active = true,
                    };

                    storeDB.AddToUsers(user);

                    storeDB.SaveChanges();
                    FormsService.SignIn(user.Username, false);
                    return RedirectToAction("Index", "Home");
                }
            }

            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        [ChildActionOnly]
        public ActionResult LogOnUserControl()
        {
            return PartialView();
        }
    }
}
